import { routerRedux } from 'dva/router'
import { login } from '../services/login'

export default {
  namespace: 'login',

  state: {
    status: null,
  },

  effects: {
    * login({ payload }, { call, put }) {
      const response = yield call(login, payload)
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      })
      // Login successfully
      if (response.code === 1) {
        yield put({
          type: 'global/queryUserInfo',
          payload: payload,
        })
        yield put(routerRedux.push('/'))
      }
    },
    * logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: null,
        },
      })
      yield put({
        type: 'global/clear',
      })
      yield put({
        type: 'menu/clear',
      })
      sessionStorage.setItem('isLogin', false)
      yield put(routerRedux.push('/login'))
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      if (payload.code === 1) {
        sessionStorage.setItem('token', payload.data.token)
        return {
          ...state,
          status: payload.code === 1 ? 'success' : null,
        }
      }
      return state
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
    },
  },
}
